import requests
import common_util
from common_util import redisUtils,config
import json

"""
主动发送消息的接口都在这里    
"""
# 1.获取token的方法
def get_token():
    # 设置请求头，指定内容类型为application/json
    headers = {
        'Content-Type': 'application/json'
    }
    # 设置请求体，这里是一个JSON字符串，包含了用户名和密码
    data = {
        "username": config.WECHAT_USERNAME,
        "password": config.WECHAT_PASSWORD
    }
    # 发送POST请求
    response = requests.post(config.WECHAT_API_URL + "/getWechatToken", headers=headers, json=data)
    # 确保请求成功
    if response.status_code == 200:
        # 解析JSON响应
        json_data = response.json()
        # 获取code和token的值
        token = json_data.get('token')
        # 将token放在redis中
        redisUtils.set_object("mxxWechatRot-python-token", token, 19 * 60)
        # 输出结果
        return token
    else:
        return ""


# 2. 37版本的发送方法
def send_public_v37(wxid, tag, appkey, message, user_nick_list=None, user_name_list=None):
    # 获取redis中的token
    redis_token = redisUtils.get_record("mxxWechatRot-python-token")
    if redis_token is None:
        redis_token = get_token()
    # 创建请求参数
    params = {
        "tag": tag,
        "chatRoomName": wxid,
        "appkey": appkey,
        "message": message,
        "version": "3730",
        "userNickList": user_nick_list,
        "userNameList": user_name_list
    }
    # 发送POST请求
    response = requests.post(
        config.WECHAT_API_URL + config.WECHAT_SENDMSG_URL,
        json.dumps(params),
        headers={
            "Authorization": "Bearer " + redis_token,
            "content-Type": "application/json"
        }
    )
    return response.text


# 3. 36版本的发送方法
def send_public_v36(wxid, tag, appkey, message,isAt,atList):
    # 获取redis中的token
    redis_token = redisUtils.get_record("mxxWechatRot-python-token")
    if redis_token is None:
        redis_token = get_token()
    # 创建请求参数
    params = {
        "tag": tag,
        "wxid": wxid,
        "appkey": appkey,
        "message": message,
        "isAt": isAt,
        "atList": atList
    }
    # 发送POST请求
    response = requests.post(
        config.WECHAT_API_URL + config.WECHAT_SENDMSG_URL,
        json.dumps(params),
        headers={
            "Authorization": "Bearer " + redis_token,
            "content-Type": "application/json"
        }
    )
    return response.text
